import selectors
from socket import *

ip_port=("localhost",1234)
back_log=5
buff_size=1024

server_socket = socket(AF_INET,SOCK_STREAM)
server_socket.bind(ip_port)
server_socket.listen(back_log)

sel=selectors.DefaultSelector()

def accept(server_socket,mask):
    conn,addr=server_socket.accept()
    print("conn",conn)
    print("addr", addr)
    conn.setblocking(False)
    sel.register(conn,selectors.EVENT_READ,read)
def read(conn,mask):
    try:
        data = conn.recv(1024)
        if not data:
            raise Exception
        print(data.decode("utf-8"))
        conn.sendall(data.upper())
        sel.unregister(conn)
        conn.close()
    except Exception as e:
        print("closeing conn",conn)
        sel.unregister(conn)
        conn.close()

sel.register(server_socket,selectors.EVENT_READ,accept)
print("sever  start walking...")
while True:
    events = sel.select()
    for key,mask in events:
        callback=key.data
        callback(key.fileobj,mask)

